import { Configuration } from 'webpack'

import { taskGroups } from '../cli/e2e-task-group'

import { pageCompilerConfigs, pageDepends, sdkCompilerConfigs, SdkDependKey } from './cypress-constants'

export function getCompilers(taskId?: string): Configuration[] {
  // taskId 无法找到时使用全量
  if (!taskId || !taskGroups[taskId]) {
    return [...Object.values(pageCompilerConfigs), ...Object.values(sdkCompilerConfigs)].flat()
  }
  if (taskId && taskGroups[taskId]) {
    const { pagePaths } = taskGroups[taskId]
    // 合并多页面 compiler 并去重
    const _pageCompilerConfigs = [...new Set(pagePaths.map((path) => pageCompilerConfigs[path]))]
    // 合并多页面依赖的 sdk compiler 并去重
    const _sdkCompilerConfigs = [
      ...new Set(pagePaths.reduce((dependKeys, path) => [...dependKeys, ...pageDepends[path]], [] as SdkDependKey[])),
    ]
      .map((dependKey) => sdkCompilerConfigs[dependKey])
      .flat()
    return [..._pageCompilerConfigs, ..._sdkCompilerConfigs]
  }
  return []
}
